import fitz
import os
import pathlib


def get_pdf_files(folder_path):
    """
    获取指定文件夹下的所有PDF文件路径

    Args:
        folder_path (str): 文件夹路径

    Returns:
        list: 包含所有PDF文件绝对路径的列表
    """
    pdf_files = []
    folder = pathlib.Path(folder_path)

    # 使用rglob递归搜索所有PDF文件
    for file_path in folder.rglob("*.pdf"):
        if file_path.is_file():
            pdf_files.append(file_path.resolve())  # 获取绝对路径

    return pdf_files


def is_directory(path):
    """
    判断给定路径是否为文件夹

    Args:
        path (str): 要检查的路径

    Returns:
        bool: 如果是文件夹返回True，否则返回False
    """
    # 方法1：使用os.path.isdir()
    if os.path.exists(path):
        return os.path.isdir(path)
    return False


# PDF转图片
def pdf_pic(doc, from_page, to_page):
    Doc = doc[0:-4]
    doc = fitz.open(doc)
    for pg in range(from_page - 1, to_page if to_page > 0 else doc.page_count):
        page = doc[pg]
        zoom = int(100)
        rotate = int(0)
        H = 20
        M = 40
        L = 60
        trans = fitz.Matrix(zoom / M, zoom / M).prerotate(rotate)
        pm = page.get_pixmap(matrix=trans, alpha=True)
        pm.save(Doc + "第%s页.png" % str(pg + 1))
    # print("操作完成!")
    p3 = "\n操作完成!\n"
    return p3


def pdf_pic_path(path):
    if is_directory(path):
        paths = get_pdf_files(path)
        for pathItem in paths:
            pdf_pic(str(pathItem), 1, 0)
    else:
        pdf_pic(path, 1, 0)


if __name__ == '__main__':
    path = 'C:\\Users\\admin\\Desktop\\测试\\（最终版）成人脑电记录仪20251015.pdf'
    if is_directory(path):
        paths = get_pdf_files(path)
        for pathItem in paths:
            pdf_pic(str(pathItem), 1, 0)
    else:
        pdf_pic(path, 1, 0)
